﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using DesignPatternToolkit.Wizard.Engine;
using DesignPatternToolkit.Core;

namespace DesignPatternToolkit.Wizard.Helpers
{
    public static class LukeFileWalker
    {
        /// <summary>
        /// Loads the available design patterns via reflection from the directory we are currently running from.
        /// </summary>
        public static List<Type> GetAvailablePatterns()
        {
            List<Type> result = new List<Type>();

            Assembly currAssembly = Assembly.GetExecutingAssembly();
            string currDir = Path.GetDirectoryName(currAssembly.Location);

            foreach (FileInfo potentialDll in new DirectoryInfo(currDir).GetFiles("*Patterns*.dll"))
            {
                try
                {
                    Assembly potentialBuilder = Assembly.LoadFrom(potentialDll.FullName);
                    if (potentialBuilder != null)
                    {
                        /* So far, so good. Let's see if there are any concrete PatternBuilder classes in here.  */
                        Type[] possibleTypes = potentialBuilder.GetTypes();
                        foreach (Type possibleType in possibleTypes)
                        {
                            if (typeof(PatternBuilder).IsAssignableFrom(possibleType) && !possibleType.IsAbstract)
                            {
                                /* Disco! */
                                result.Add(possibleType);
                            }
                        }
                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.Message);
                    // do nothing...
                }
            }

            return result;
        }
    }
}
